// pages/statistics/statistics.js
import * as echarts from '../../ec-canvas/echarts';
import { ledgerConfig, ledgerTools } from '../../utils/ledgerTools'
import { formatTime, formatTimeTwo } from "../../utils/util"

Page({
  /**
   * 页面的初始数据
   */
  data: {
    ecpie: {
      lazyLoad: true
    },
    ecbar: {
      lazyLoad: true
    },
    pieOption: {
      title: {
        text: '月内消费方式占比',
        left: 'center',
        top: 'center'
      },
      series: {
        type: 'pie',
        data: [],
        avoidLabelOverlap: true,
        emphasis: { label: { show: true, fontSize: '15', fontWeight: 'bold' } },
        center: ['50%', '50%'],
        radius: ['45%', '75%'],
        itemStyle: { normal: { label: { show: true, formatter: '{b}\n{c}元({d}%)' }, labelLine: { show: true } } }
      }
    },
    barOption: {
      title: { text: '月内日收支情况', left: 'center', top: '0' },
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, confine: true },
      legend: { data: ledgerConfig.type, top: "6%" },
      grid: { left: 10, right: 10, bottom: 30, top: "18%", containLabel: true },
      yAxis: { type: 'value', axisLine: { lineStyle: { color: '#999' } }, axisLabel: { color: '#666' } },
      xAxis: {
        type: 'category', data: [], axisTick: { show: true },
        axisLine: { lineStyle: { color: '#999' } }, axisLabel: { margin: 10, rotate: -90, interval: 0, olor: '#666' },
        splitLine: { show: true, lineStyle: { color: '#0735a2', width: 1, type: 'dashed' } },
      },
      dataZoom: [{ type: 'slider', show: true, left: 'center', bottom: 0, width: "55%", zoomLoxk: true, height: 30, }],
      series: [
        { name: '收入', type: 'bar', data: [], stack: '总量', label: { normal: { show: true, position: 'left' } } },
        { name: '支出', type: 'bar', data: [], stack: '总量', label: { normal: { show: true } } },
        { name: '不计收支', type: 'bar', data: [], label: { normal: { show: true, position: 'inside' } } }
      ]
    },
    nowDate: "",
  },

  loadData(yearAndMonth){
    const ldType = ledgerConfig().type
    const ldCG = ledgerConfig().category
    const pieResult = []
    const barResult = { xAxis: [], sumMIC: [], sumMEC: [], sumMNIC: [] }
    const date = formatTimeTwo(formatTime(yearAndMonth), "Y-M")
    const ledgerDataByDate = ledgerTools.getDataByDate(date) || []
    ledgerDataByDate.filter((v, i, s) => v.type == ldType.indexOf("支出"))
      .forEach(item => pieResult.push({ name: ldCG[item.category].name, value: item.money }));
    pieResult.sort((a, b) => a.value - b.value)

    const ledgerDGBD = ledgerTools.getDataDateGroupByDay(date)
    for (const key in ledgerDGBD) {
      const MIC = ledgerDGBD[key].reduce((x, y) => x + (y.type == ldType.indexOf("收入") ? y.money : 0), 0)
      const MEC = ledgerDGBD[key].reduce((x, y) => x + (y.type == ldType.indexOf("支出") ? 0 - y.money : 0), 0)
      const MNIC = ledgerDGBD[key].reduce((x, y) => x + (y.type == ldType.indexOf("不计收支") ? y.money : 0), 0)
      barResult['xAxis'].unshift(key)
      barResult['sumMIC'].unshift(MIC)
      barResult['sumMEC'].unshift(MEC)
      barResult['sumMNIC'].unshift(MNIC)
    }
    this.setData({
      'pieOption.series.data': pieResult,
      'barOption.xAxis.data': barResult['xAxis'],
      'barOption.series[0].data': barResult['sumMIC'],
      'barOption.series[1].data': barResult['sumMEC'],
      'barOption.series[2].data': barResult['sumMNIC'],
      nowDate: formatTimeTwo(date, "Y年M月")
    })
    if (typeof this.getTabBar === 'function' && this.getTabBar()) { this.getTabBar().setData({ selected: 2 }) }
    this.selectComponent("#pie").init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, { width: width, height: height, devicePixelRatio: dpr });
      chart.setOption(this.data.pieOption)
      return chart;
    })
    this.selectComponent("#bar").init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, { width: width, height: height, devicePixelRatio: dpr });
      chart.setOption(this.data.barOption)
      return chart;
    })
  },
  /*切换日期 */
  pagechange: function () {
    const data = []
    const _self = this
    ledgerTools.getData().forEach(e => {
      const yearAndMonth = formatTimeTwo(formatTime(new Date(e.date)), "Y-M")
      if (data.indexOf(yearAndMonth) == -1) { data.push(yearAndMonth) }
    });
    wx.showActionSheet({ itemList: data, success: function (res) { _self.loadData(new Date(data[res.tapIndex])) } })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadData(new Date())
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})